/*
 * Copyright (C) 2022 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.arthas.psimobile.fragment.login;

import android.graphics.Color;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;

import com.arthas.psimobile.core.BaseFragment;
import com.arthas.psimobile.utils.UrlAddress;
import com.xuexiang.psimobile.R;
import com.xuexiang.psimobile.databinding.FragmentForgetPasswdBinding;
import com.arthas.psimobile.utils.XToastUtils;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.utils.CountDownButtonHelper;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.ThemeUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.w3c.dom.Entity;

/**
 * 找回密码
 *
 * @author Arthas
 * @since 2022-4-2 9:32
 */
@Page(anim = CoreAnim.none)
public class ForgetPasswdFragment extends BaseFragment<FragmentForgetPasswdBinding> implements View.OnClickListener {

    private CountDownButtonHelper mCountDownHelper;

    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle()
                .setImmersive(true);
        titleBar.setBackgroundColor(Color.TRANSPARENT);
        titleBar.setTitle("");
        titleBar.setLeftImageDrawable(ResUtils.getVectorDrawable(getContext(), R.drawable.ic_login_close));
        titleBar.setActionTextColor(ThemeUtils.resolveColor(getContext(), R.attr.colorAccent));
        return titleBar;
    }

    @SingleClick
    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.btn_reset_passwd) {
            if (binding.etPhoneNumber.validate()) {
                if (binding.etPasswd.validate()) {
                    if (binding.etConfirmPasswd.validate()) {
                        if (binding.etConfirmPasswd.getEditValue().equals(binding.etPasswd.getEditValue())) {
                            if (binding.etVerifyCode.validate()) {
                                onChangePw(binding.etPhoneNumber.getEditValue(), binding.etPasswd.getEditValue());
                            }
                        } else {
                            XToastUtils.warning("两次密码输入不一致");
                        }
                    }
                }
            }
        } else if (id == R.id.btn_get_verify_code) {
            if (binding.etPhoneNumber.validate()) {
                getVerifyCode(binding.etPhoneNumber.getEditValue());
            }
        }
    }

    @NonNull
    @Override
    protected FragmentForgetPasswdBinding viewBindingInflate(LayoutInflater inflater, ViewGroup container) {
        return FragmentForgetPasswdBinding.inflate(inflater, container, false);
    }

    @Override
    protected void initViews() {
        mCountDownHelper = new CountDownButtonHelper(binding.btnGetVerifyCode, 60);
    }

    @Override
    protected void initListeners() {
        binding.btnResetPasswd.setOnClickListener(this);
        binding.btnGetVerifyCode.setOnClickListener(this);
    }

    /**
     * 获取验证码
     */
    private void getVerifyCode(String phoneNumber) {
        XToastUtils.warning("只是演示，验证码随便输");
        mCountDownHelper.start();
    }

    private void onChangePw(String phoneNumber, String passwd) {

        new Thread() {
            @Override
            public void run() {
                try {
                    Looper.prepare();
                    String requestUrl = UrlAddress.urlAddress + "/account/updatepasswd";
                    HttpPut request = new HttpPut(requestUrl);

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("phoneNumber", phoneNumber);
                    jsonObject.put("newPasswd", passwd);
                    StringEntity se = new StringEntity(jsonObject.toString(), HTTP.UTF_8);
                    request.setEntity(se);
                    request.addHeader("Content-Type", "application/json");
                    HttpResponse httpResponse = new DefaultHttpClient().execute(request);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        String retSrc = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
                        JSONObject json = new JSONObject(retSrc);
                        int code = json.getInt("code");
                        if (code == 0) {
                            XToastUtils.success("修改成功");
                            openNewPage(LoginFragment.class);
                        } else {
                            XToastUtils.toast(json.getString("msg"));
                        }
                    }
                    Looper.loop();
                } catch (Exception e) {
                    Log.e("ChangePw Error", e.toString());
                }
            }
        }.start();
    }
}
